package com.hc.appanimal;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;
import com.hc.DTO.AnimalCategoryMasterDTO;
import com.hc.DTO.AnimalDTO;
import com.hc.DTO.AnimalImagesDTO;
import com.hc.DTO.LoginDTO;
import com.hc.DTO.SysAnimalDTO;
import com.hc.DTO.TokenDTO;
import com.hc.DTO.notificationDTO;
import com.hc.constants.Constants;
import com.hc.model.utils.AnimalCategoryMasterModel;
import com.hc.model.utils.AnimalImagesModel;
import com.hc.model.utils.AnimalModel;
import com.hc.model.utils.LoginModel;
import com.hc.model.utils.SysAnimalModel;
import com.hc.model.utils.TokenModel;
import com.hc.model.utils.notificationModel;
import com.hc.webservice.InternetUtils;
import com.hc.webservice.ServiceHandler;
import com.yyxu.download.utils.MyIntents;
import com.yyxu.download.utils.StorageUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import static com.hc.appanimal.ServerTask.*;

public class LoginActivity extends Activity implements OnClickListener {
	EditText edEmail, edPassword;
	Button btnLogin, btnCheckEmail, btnCheckPassword;
	Dialog dialog, dialog1, dialog2, dialog3, dialog4;
	AnimationDrawable frameAnimation, frameAnimation1, frameAnimation2,
			frameAnimation3, frameAnimation4;
	AsyncTask<Void, Void, Void> gcmRegisterTask;
	public boolean flagExpires = false;
	SimpleDateFormat sdf;
	int size = 0;
	public boolean flagDialog = true;
	final BroadcastReceiver handleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			setResultCode(Activity.RESULT_OK);
			Log.i(TAG, newMessage);
		}
	};

	@SuppressLint("SimpleDateFormat")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			StorageUtils.mkdirApp();
			StorageUtils.mkdir();
		} catch (IOException e) {
			e.printStackTrace();
		}
		setContentView(R.layout.activity_login);
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		TokenModel tokenModel = TokenModel.getInstance();
		TokenDTO tokenDTO = tokenModel.getToken(LoginActivity.this);
		String dateExpires = tokenDTO.getExpires();

		Date date2 = null;
		Date date1 = null;
		String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
		SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.ENGLISH);
		String currentDayExpires = format.format(new Date());

		try {
			LoginModel modelLogin = LoginModel.getInstance();
			LoginDTO dtogetLogin = modelLogin
					.getUserNamePassword(LoginActivity.this);
			date1 = format.parse(currentDayExpires);
			date2 = format.parse(dateExpires);
			if (date1.compareTo(date2) < 0) {
				flagExpires = true;
				if (dtogetLogin.getFlag() >= 1) {
					if (InternetUtils.getInstance()
							.isConnectingToInternet(this)) {
						SysAnimalModel model = SysAnimalModel.getInstance();
						SysAnimalDTO dtosys = model
								.getLastTwoDay(LoginActivity.this);
						String currentDaySql = dtosys.getCurrentday();
						int year = 0;
						int mon = 0;
						int day = 0;
						if (!currentDaySql.equalsIgnoreCase("")) {
							year = Integer.parseInt(currentDaySql.substring(0,
									4));
							mon = Integer.parseInt(currentDaySql
									.substring(5, 7));
							day = Integer.parseInt(currentDaySql.substring(8,
									10));
						}

						String currentDay = sdf.format(new Date());
						int currYear = 0;
						int currMon = 0;
						int currDay = 0;
						if (!currentDay.equalsIgnoreCase("")) {
							currYear = Integer.parseInt(currentDay.substring(0,
									4));
							currMon = Integer.parseInt(currentDay.substring(5,
									7));
							currDay = Integer.parseInt(currentDay.substring(8,
									10));
						}
						boolean flagUpdate = false;
						if (currYear > year) {
							flagUpdate = true;
							new VerySlowTaskLogin(dtogetLogin, flagUpdate,
									currentDaySql).execute();
						} else if (currMon > mon) {
							flagUpdate = true;
							new VerySlowTaskLogin(dtogetLogin, flagUpdate,
									currentDaySql).execute();
						} else if (currDay > day + 1) {
							flagUpdate = true;
							new VerySlowTaskLogin(dtogetLogin, flagUpdate,
									currentDaySql).execute();
						} else {
							new VerySlowTaskLogin(dtogetLogin, flagUpdate,
									currentDaySql).execute();
						}
					} else {
						if (dtogetLogin.getFlag() >= 1) {
							Intent intent = new Intent(LoginActivity.this,
									HomeActivity.class);
							Bundle data = new Bundle();
							data.putInt("key_GMC", 0);
							intent.putExtras(data);
							startActivity(intent);
							finish();
						}
					}
				}
			}

		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}

		edEmail = (EditText) findViewById(R.id.edEmail);
		edPassword = (EditText) findViewById(R.id.edPassword);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(this);
		btnCheckEmail = (Button) findViewById(R.id.btnCheckEmail);
		btnCheckPassword = (Button) findViewById(R.id.btnCheckPassword);

		//
	}

	// login
	public class VerySlowTaskLogin extends AsyncTask<Void, Void, Void> {
		final ServiceHandler sh = new ServiceHandler();
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		String err = "";
		String success = "";
		String strerr = "";

		boolean flagUpdate = false;
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateupdate = ""; // = sdf.format(new Date());
		// String dateupdate = "1989-01-01";
		String key = "";
		String _result = "";

		TokenDTO toke;
		String regId = "";
		LoginDTO dtoLogin;
		boolean isFalse = false;
		public VerySlowTaskLogin(LoginDTO _dto, boolean _flagUpdate,
				String _dateupdate) {
			dtoLogin = _dto;
			flagUpdate = _flagUpdate;
			dateupdate = _dateupdate;
			dialog = new Dialog(LoginActivity.this, R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {

			if (!flagExpires) {
				nameValuePairs.add(new BasicNameValuePair("username", dtoLogin
						.getUserName()));
				nameValuePairs.add(new BasicNameValuePair("grant_type",
						"password"));
				nameValuePairs.add(new BasicNameValuePair("password", dtoLogin
						.getPassWord()));

			} else {

				nameValuePairs.add(new BasicNameValuePair("username", dtoLogin
						.getUserName()));
				nameValuePairs.add(new BasicNameValuePair("grant_type",
						"password"));
				nameValuePairs.add(new BasicNameValuePair("password", dtoLogin
						.getPassWord()));
			}
			String jsonStr = sh.makeServiceCall(Constants.URL_LOGIN,
					ServiceHandler.POST, nameValuePairs);

			// String jsonStr = excutePost(Constants.URL_LOGIN,
			// "grant_type=password&username=vsj_1987@yahoo.com&password=Admin@12345");
			try {
				JSONObject object1;
				object1 = new JSONObject(jsonStr);
				for (@SuppressWarnings("unchecked")
				Iterator<String> iter = object1.keys(); iter.hasNext();) {
					String key = iter.next();
					if (key.equalsIgnoreCase("error_description")) {
						strerr = object1.getString("error_description");
						_result = strerr;
						isFalse = true;
					} else if (key.equalsIgnoreCase("access_token")) {
						// finish
						String access_token = object1.getString("access_token");
						_result = key;
						String token_type = object1.getString("token_type");
						String expires = object1.getString(".expires");
						toke = new TokenDTO();
						toke.setAccess_token(access_token);
						toke.setToken_type(token_type);
						toke.setExpires(expires);
						TokenModel tokenModel = TokenModel.getInstance();
						tokenModel.updateToken(toke, LoginActivity.this);

						int Flag = dtoLogin.getFlag();
						Flag = Flag + 1;

						dtoLogin.setUserName(dtoLogin.getUserName());
						dtoLogin.setPassWord(dtoLogin.getPassWord());
						dtoLogin.setFlag(Flag);
						LoginModel modelLogin = LoginModel.getInstance();
						modelLogin.updateLogin(dtoLogin, LoginActivity.this);
					}

				}

			} catch (Exception e) {
			}

			return null;

		}

		protected void xuLyDangKyGCMServer() {
			// Make sure the device has the proper dependencies.
			GCMRegistrar.checkDevice(LoginActivity.this);
			// Make sure the manifest was properly set - comment out this
			// line
			// while developing the app, then uncomment it when it's ready.
			GCMRegistrar.checkManifest(LoginActivity.this);

			// msg = (TextView) findViewById(R.id.display);

			registerReceiver(handleMessageReceiver, new IntentFilter(
					DISPLAY_MESSAGE_ACTION));
			regId = GCMRegistrar.getRegistrationId(LoginActivity.this);

			if (regId.equals("")) {
				// Automatically registers application on startup.
				GCMRegistrar.register(LoginActivity.this, SENDER_ID);
			} else {
				// Device is already registered on GCM, check server.
				if (GCMRegistrar.isRegisteredOnServer(LoginActivity.this)) {
					// Skips registration.
					// msg.append(getString(R.string.already_registered) +
					// "\n");
					;
					final Context context = LoginActivity.this;
					gcmRegisterTask = new AsyncTask<Void, Void, Void>() {

						@Override
						protected Void doInBackground(Void... params) {
							boolean registered = ServerTask.register(context,
									regId);
							// At this point all attempts to register with
							// the
							// app
							// server failed, so we need to unregister the
							// device
							// from GCM - the app will try to register again
							// when
							// it is restarted. Note that GCM will send an
							// unregistered callback upon completion, but
							// GCMIntentService.onUnregistered() will ignore
							// it.
							if (!registered) {
								GCMRegistrar.unregister(context);
							}
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
							gcmRegisterTask = null;
						}

					};
					gcmRegisterTask.execute(null, null, null);
				} else {
					// Try to register again, but not in the UI thread.
					// It's also necessary to cancel the thread onDestroy(),
					// hence the use of AsyncTask instead of a raw thread.
					final Context context = LoginActivity.this;
					gcmRegisterTask = new AsyncTask<Void, Void, Void>() {

						@Override
						protected Void doInBackground(Void... params) {
							boolean registered = ServerTask.register(context,
									regId);
							// At this point all attempts to register with
							// the
							// app
							// server failed, so we need to unregister the
							// device
							// from GCM - the app will try to register again
							// when
							// it is restarted. Note that GCM will send an
							// unregistered callback upon completion, but
							// GCMIntentService.onUnregistered() will ignore
							// it.
							if (!registered) {
								GCMRegistrar.unregister(context);
							}
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
							gcmRegisterTask = null;
						}

					};
					gcmRegisterTask.execute(null, null, null);
				}
			}

		}
//here
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			dialog.dismiss();
			frameAnimation.stop();
			/*
			 * _result
					.equalsIgnoreCase("The user name or password is incorrect.")
			 */
			if (isFalse) {
				isFalse=false;
				final Dialog dialogerr = new Dialog(LoginActivity.this,
						android.R.style.Theme_Translucent);
				dialogerr.requestWindowFeature(Window.FEATURE_NO_TITLE);

				dialogerr.setCancelable(true);
				dialogerr.setContentView(R.layout.dialog_err);
				TextView txtContent = (TextView) dialogerr
						.findViewById(R.id.txtContent);
				txtContent.setText(strerr);
				Button btnOke = (Button) dialogerr.findViewById(R.id.bntOk);

				btnOke.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogerr.dismiss();
					}
				});

				dialogerr.show();
			} else if (_result.equalsIgnoreCase("access_token")) {

				if (!flagUpdate && dtoLogin.getFlag() >= 1) {
					Intent intent = new Intent(LoginActivity.this,
							HomeActivity.class);
					Bundle data = new Bundle();
					notificationModel notimodel = notificationModel
							.getInstance();
					notificationDTO notidto = notimodel
							.getToken(LoginActivity.this);
					if (notidto.getFlag() == 0) {

						xuLyDangKyGCMServer();
						if (!regId.equalsIgnoreCase("")) {
							notimodel.updateToken(notidto, LoginActivity.this);
							data.putInt("key_GMC", 1);
							data.putString("regId", regId);
							intent.putExtras(data);
							startActivity(intent);
							finish();
						}
						// demo
						// else {
						// data.putInt("key_GMC", 0);
						// data.putString("regId", regId);
						// intent.putExtras(data);
						// startActivity(intent);
						// finish();
						// }
						// end demo
					} else {
						data.putInt("key_GMC", 0);
						data.putString("regId", regId);
						intent.putExtras(data);
						startActivity(intent);
						finish();
					}

				} else {
					xuLyDangKyGCMServer();
					new VerySlowTaskUploadImages(dateupdate, dtoLogin, regId)
							.execute();

				}

			}

		}

	}

	public final static boolean isValidEmail(CharSequence target) {
		return !TextUtils.isEmpty(target)
				&& android.util.Patterns.EMAIL_ADDRESS.matcher(target)
						.matches();
	}

	public boolean isValidInput(String email) {
		if (!isValidEmail(email)) {
			new AlertDialog.Builder(this)
					.setTitle("Error!")
					.setMessage("This email invalid, please input again.")
					.setPositiveButton(android.R.string.yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									// continue with delete
								}
							})
					/*
					 * .setNegativeButton(android.R.string.no, new
					 * DialogInterface.OnClickListener() { public void
					 * onClick(DialogInterface dialog, int which) { // do
					 * nothing } })
					 */
					.setIcon(android.R.drawable.ic_dialog_alert).show();
			return false;
		}
		// get 3 number first.

		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnLogin:
			if (InternetUtils.getInstance().isConnectingToInternet(this)) {
				String strEmail = edEmail.getText().toString();
				String strPassword = edPassword.getText().toString();
				if (strEmail.equalsIgnoreCase("") || !isValidInput(strEmail)) {
					btnCheckEmail.setVisibility(View.VISIBLE);
					btnCheckEmail.setBackgroundResource(R.drawable.check_false);
				} else {
					btnCheckEmail.setVisibility(View.VISIBLE);
					btnCheckEmail.setBackgroundResource(R.drawable.check_true);
				}
				if (strPassword.equalsIgnoreCase("")) {
					btnCheckPassword.setVisibility(View.VISIBLE);
					btnCheckPassword
							.setBackgroundResource(R.drawable.check_false);
				} else {
					btnCheckPassword.setVisibility(View.VISIBLE);
					btnCheckPassword
							.setBackgroundResource(R.drawable.check_true);
				}
				LoginDTO dto = new LoginDTO();
				dto.setUserName(strEmail);
				dto.setPassWord(strPassword);
				dto.setFlag(1);
				if (!strEmail.equalsIgnoreCase("")
						&& !strPassword.equalsIgnoreCase("")) {
					if (isValidInput(strEmail)) {
						if (InternetUtils.getInstance().isConnectingToInternet(
								this)) {
							// update sys

							// new VerySlowTaskLogin(dto).execute();
							SysAnimalModel model = SysAnimalModel.getInstance();
							SysAnimalDTO dtosys = model
									.getLastTwoDay(LoginActivity.this);
							String currentDaySql = dtosys.getCurrentday();
							String dateupdate = dtosys.getDateupdate();
							int year = 0;
							int mon = 0;
							int day = 0;
							if (!currentDaySql.equalsIgnoreCase("")) {
								year = Integer.parseInt(currentDaySql
										.substring(0, 4));
								mon = Integer.parseInt(currentDaySql.substring(
										5, 7));
								day = Integer.parseInt(currentDaySql.substring(
										8, 10));
							}
							String currentDay = sdf.format(new Date());
							int currYear = 0;
							int currMon = 0;
							int currDay = 0;
							if (!currentDay.equalsIgnoreCase("")) {
								currYear = Integer.parseInt(currentDay
										.substring(0, 4));
								currMon = Integer.parseInt(currentDay
										.substring(5, 7));
								currDay = Integer.parseInt(currentDay
										.substring(8, 10));
							}
							boolean flagUpdate = false;
							if (currYear > year) {
								flagUpdate = true;
								new VerySlowTaskLogin(dto, flagUpdate,
										dateupdate).execute();
							} else if (currMon > mon) {
								flagUpdate = true;
								new VerySlowTaskLogin(dto, flagUpdate,
										dateupdate).execute();
							} else if (currDay > day + 1) {
								flagUpdate = true;
								new VerySlowTaskLogin(dto, flagUpdate,
										dateupdate).execute();
							} else {
								new VerySlowTaskLogin(dto, flagUpdate,
										dateupdate).execute();
							}
						}

					}

				}

			} else {

				LoginModel modelLogin = LoginModel.getInstance();
				LoginDTO dtoLogin = modelLogin
						.getUserNamePassword(LoginActivity.this);
				if (dtoLogin.getFlag() >= 1) {
					if (edEmail.getText().toString()
							.equalsIgnoreCase(dtoLogin.getUserName())
							&& edPassword.getText().toString()
									.equalsIgnoreCase(dtoLogin.getPassWord())) {
						Intent intent = new Intent(LoginActivity.this,
								HomeActivity.class);
						Bundle data = new Bundle();
						data.putInt("key_GMC", 0);
						intent.putExtras(data);
						startActivity(intent);
						finish();
					} else {
						Toast.makeText(LoginActivity.this,
								"user name or password isn't incorrect",
								Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(
							LoginActivity.this,
							"Your registration is under review. You will get an email when your account is approved. You can login after your account is approved.",
							Toast.LENGTH_LONG).show();
				}

			}

			break;

		default:
			break;
		}

	}

	// sysAnimal
	public class VerySlowTaskUploadImages extends AsyncTask<Void, Void, Void> {
		String dateupdate = "";
		String regId;
		TokenModel tokenModel = TokenModel.getInstance();
		TokenDTO token = tokenModel.getToken(LoginActivity.this);
		String messageerr = "";
		LoginDTO dtoLogin;
		boolean flag = false;
		String strJson = "";
		ArrayList<String> arrImgSave;

		public VerySlowTaskUploadImages(String _dateupdate, LoginDTO _dtoLogin,
				String _regId) {
			regId = _regId;
			dtoLogin = _dtoLogin;
			dateupdate = _dateupdate;
			arrImgSave = new ArrayList<String>();
			dialog1 = new Dialog(LoginActivity.this, R.style.NewDialog);
			dialog1.setContentView(R.layout.loading);

			dialog1.setCancelable(false);

			dialog1.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation1 = (AnimationDrawable) dialog1.findViewById(
					R.id.loading_icon).getBackground();
			TextView localTextView = (TextView) dialog1.findViewById(16908310);
			localTextView.setText("Downloading data\n Please wait");
			localTextView.setTextSize(25.0F);
			localTextView.setGravity(Gravity.CENTER_VERTICAL
					| Gravity.CENTER_HORIZONTAL);
			dialog1.show();
			frameAnimation1.start();

		}

		@Override
		protected Void doInBackground(Void... params) {

			HttpClient client = new DefaultHttpClient();
			HttpGet method = new HttpGet(Constants.URL_ANIMAL + dateupdate);
			method.setHeader("Content-Type",
					"application/x-www-form-urlencoded;iso-8859-1");
			method.setHeader("Authorization", token.getToken_type() + " "
					+ token.getAccess_token());
			try {
				HttpResponse response = client.execute(method);
				response.getEntity();

				BufferedReader br = new BufferedReader(new InputStreamReader(
						(response.getEntity().getContent())));
				String output;
				System.out.println("Output from Server .... \n");
				StringBuilder builder = new StringBuilder();
				while ((output = br.readLine()) != null) {
					System.out.println(output);
					builder.append(output);
				}

				strJson = builder.toString();
				if (strJson != null) {
					SysAnimalModel modelSys = SysAnimalModel.getInstance();
					SysAnimalDTO dtoSys = new SysAnimalDTO();
					String currentDay = sdf.format(new Date());
					dtoSys.setCurrentday(currentDay);
					modelSys.updateSysAnimal(dtoSys, LoginActivity.this);

					JSONArray jsonArr = new JSONArray(strJson);

					// if (jsonArr.length() > 0) {
					for (int i = 0; i < jsonArr.length(); i++) {
						JSONObject obj = jsonArr.getJSONObject(i);
						int IdAnimal = obj.getInt("Id");
						String CommonName = obj.getString("CommonName");
						String ScientificName = obj.getString("ScientificName");
						String RegionalName = obj.getString("RegionalName");
						String WLPA = obj.getString("WLPA");
						String IUCN = obj.getString("IUCN");
						String CITES = obj.getString("CITES");
						String SmallNote = obj.getString("SmallNote");
						String TradeInfo = obj.getString("TradeInfo");
						String MoreInfo = obj.getString("MoreInfo");
						String TradeMapDesc = obj.getString("TradeMapDesc");
						String TradeMapCoords = obj.getString("TradeMapCoords");
						String UpdatedOn = obj.getString("UpdatedOn");
						String ContentGuid = obj.getString("ContentGuid");
						String UserId = obj.getString("UserId");
						int AnimalCategoryId = obj.getInt("AnimalCategoryId");
						AnimalDTO animalDTO = new AnimalDTO();
						animalDTO.setId(IdAnimal);
						animalDTO.setCommonName(CommonName);
						animalDTO.setScientificName(ScientificName);
						animalDTO.setRegionalName(RegionalName);
						animalDTO.setwLPA(WLPA);
						animalDTO.setiUCN(IUCN);
						animalDTO.setcITES(CITES);
						animalDTO.setSmallNote(SmallNote);
						animalDTO.setTradeInfo(TradeInfo);
						animalDTO.setMoreInfo(MoreInfo);
						animalDTO.setTradeMapDesc(TradeMapDesc);
						animalDTO.setTradeMapCoords(TradeMapCoords);
						animalDTO.setUpdatedOn(UpdatedOn);
						animalDTO.setContentGuid(ContentGuid);
						animalDTO.setUserId(UserId);
						animalDTO.setAnimalCategoryId(AnimalCategoryId);
						// update database

						AnimalModel modelAnimal = AnimalModel.getInstance();
						boolean flag = modelAnimal.getIdAnimal(
								LoginActivity.this, IdAnimal);
						if (!flag) {
							modelAnimal.insertAnimal(animalDTO,
									LoginActivity.this);
						} else {
							modelAnimal.updateAnimal(animalDTO,
									LoginActivity.this);
						}

						JSONArray arrImg = obj.getJSONArray("AnimalImages");
						for (int j = 0; j < arrImg.length(); j++) {
							JSONObject objImg = arrImg.getJSONObject(j);
							int Id = objImg.getInt("Id");
							int AnimalId = objImg.getInt("AnimalId");
							String ImageUrl = objImg.getString("ImageUrl");
							ImageUrl = ImageUrl.replaceAll(" ", "%20");

							// save images in disk
							if (ImageUrl != null) {
								arrImgSave.add(ImageUrl);
							}

							String ImageName = objImg.getString("ImageName");
							String ActualName = objImg.getString("ActualName");
							String Description = objImg
									.getString("Description");
							AnimalImagesDTO dto = new AnimalImagesDTO();
							dto.setId(Id);
							dto.setAnimalId(AnimalId);
							dto.setImageUrl(ImageUrl);
							dto.setImageName(ImageName);
							dto.setActualName(ActualName);
							dto.setDescription(Description);
							AnimalImagesModel modelImg = AnimalImagesModel
									.getInstance();
							boolean checkImg = modelImg.getIdImges(
									LoginActivity.this, Id);
							if (!checkImg) {
								modelImg.insertImages(dto, LoginActivity.this);
							} else {
								modelImg.updateImamges(dto, LoginActivity.this);
							}

							// arrData.add(dto);

						}

					}

				}

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			} catch (JSONException e) {
				flag = true;
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			size = arrImgSave.size();
			dialog1.dismiss();
			frameAnimation1.stop();
			
			if (flag) {
				final Dialog dialogerr = new Dialog(LoginActivity.this,
						android.R.style.Theme_Translucent);
				dialogerr.requestWindowFeature(Window.FEATURE_NO_TITLE);

				dialogerr.setCancelable(true);
				dialogerr.setContentView(R.layout.dialog_err);
				TextView txtContent = (TextView) dialogerr
						.findViewById(R.id.txtContent);
				txtContent
						.setText("Your registration is under review. You will get an email when your account is approved. You can login after your account is approved.");
				Button btnOke = (Button) dialogerr.findViewById(R.id.bntOk);

				btnOke.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogerr.dismiss();
						Intent intent = new Intent(LoginActivity.this,
								Main.class);
						startActivity(intent);
						finish();

					}
				});

				dialogerr.show();
			} else if (!strJson.equalsIgnoreCase("[]")) {
				if (size > 0) {
					flagDialog = false;
					new DownloadFileFromURL(arrImgSave, regId).execute();
				}else{
					new VerySlowTaskCategory(regId).execute();
				}

				
			} 
			else if (strJson.equalsIgnoreCase("[]")) {
				new VerySlowTaskCategory(regId).execute();

			}

		}

	}

	class DownloadFileFromURL extends AsyncTask<Void, String, String> {

		// String urlDowload = "";
		ArrayList<String> arrImgSave;
		String regId = "";

		public DownloadFileFromURL(ArrayList<String> arrDowload, String _regId) {

			arrImgSave = arrDowload;
			regId = _regId;
			dialog4 = new Dialog(LoginActivity.this, R.style.NewDialog);
			dialog4.setContentView(R.layout.loading);

			dialog4.setCancelable(false);

			dialog4.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation4 = (AnimationDrawable) dialog4.findViewById(
					R.id.loading_icon).getBackground();
			TextView localTextView = (TextView) dialog4.findViewById(16908310);
			localTextView.setText("Downloading data\n Please wait");
			localTextView.setTextSize(25.0F);
			localTextView.setGravity(Gravity.CENTER_VERTICAL
					| Gravity.CENTER_HORIZONTAL);
			dialog4.show();
			frameAnimation4.start();
		}

		@Override
		protected String doInBackground(Void... param) {
			int count;
			try {
				ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo netInfo = cm.getActiveNetworkInfo();

				if (netInfo != null && netInfo.isConnected()) {
					for (String urlDowload : arrImgSave) {
						String[] strsFile = urlDowload.split("/");
						File f = new File(
								Environment.getExternalStorageDirectory() + "/"
										+ Constants.APP_NAME + "/"
										+ strsFile[4] + "/" + strsFile[5]);
						if (!f.exists()) {
							URL url = new URL(urlDowload);

							HttpURLConnection conection = (HttpURLConnection) url
									.openConnection();

							conection.setRequestProperty("Connection", "close");
							conection.setConnectTimeout(2000); // Timeout 2
																// seconds.
							conection.connect();

							if (conection.getResponseCode() == 200) // Successful
																	// response.
							{
								// getting file length
								// input stream to read file - with 8k buffer
								InputStream input = new BufferedInputStream(
										url.openStream(), 8192);
								String[] strs = urlDowload.split("/");
								// Output stream to write file
								OutputStream output = new FileOutputStream(
										new File(StorageUtils.FILE_ROOT,
												strs[5]));

								byte data[] = new byte[1024];

								long total = 0;

								while ((count = input.read(data)) != -1) {
									total += count;
									// writing data to file
									output.write(data, 0, count);
									size--;
								}

								// flushing output
								output.flush();

								// closing streams
								output.close();
								input.close();

							} else {
								//
							}
						}

					}

				} else {
				}

			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}

			return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			dialog4.dismiss();
			frameAnimation4.stop();
			new VerySlowTaskCategory(regId).execute();
		}

	}


	public class VerySlowTaskDelete extends AsyncTask<Void, Void, Void> {

		TokenModel tokenModel = TokenModel.getInstance();
		TokenDTO token = tokenModel.getToken(LoginActivity.this);
		String regId = "";

		public VerySlowTaskDelete(String _regId) {
			regId = _regId;
			if(flagDialog){
				dialog3 = new Dialog(LoginActivity.this, R.style.NewDialog);
				dialog3.setContentView(R.layout.loading);

				dialog3.setCancelable(false);
				dialog3.findViewById(R.id.loading_icon).setBackgroundResource(
						R.drawable.spin_animation);
				frameAnimation3 = (AnimationDrawable) dialog3.findViewById(
						R.id.loading_icon).getBackground();
				dialog3.show();
				frameAnimation3.start();
			}
			
		}

		@Override
		protected Void doInBackground(Void... params) {

			HttpClient client = new DefaultHttpClient();
			HttpGet method = new HttpGet(Constants.URL_DELETE_ANIMAL);
			method.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			method.setHeader("Authorization", token.getToken_type() + " "
					+ token.getAccess_token());
			try {
				HttpResponse response = client.execute(method);
				response.getEntity();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						(response.getEntity().getContent())));
				String output;
				System.out.println("Output from Server .... \n");
				StringBuilder builder = new StringBuilder();
				while ((output = br.readLine()) != null) {
					System.out.println(output);
					builder.append(output);
				}

				String strJson = builder.toString();
				if (strJson != null) {
					JSONArray jsonArr = new JSONArray(strJson);
					JSONObject jsonAnimals = jsonArr.getJSONObject(0);
					JSONObject jsonAnimalImages = jsonArr.getJSONObject(1);

					JSONArray arrIdSAnimals = jsonAnimals.getJSONArray("Ids");
					JSONArray arrIdSAnimalImages = jsonAnimalImages
							.getJSONArray("Ids");

					for (int j = 0; j < arrIdSAnimals.length(); j++) {
						int number = arrIdSAnimals.getInt(j);
						AnimalDTO dtoDL = new AnimalDTO();
						dtoDL.setArrIdRemove(number);
						AnimalModel modelDelete = AnimalModel.getInstance();
						modelDelete.deleteAnimal(dtoDL, LoginActivity.this);

					}
					for (int k = 0; k < arrIdSAnimalImages.length(); k++) {
						AnimalImagesDTO dtoImgDLT = new AnimalImagesDTO();
						int numberIMG = arrIdSAnimalImages.getInt(k);
						dtoImgDLT.setIdImgeDelete(numberIMG);
						AnimalImagesModel modelDeleteIMG = AnimalImagesModel
								.getInstance();
						modelDeleteIMG.deleteAnimalIMG(dtoImgDLT,
								LoginActivity.this);

					}

				}

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if(flagDialog){
				dialog3.dismiss();
				frameAnimation3.stop();
			}
			
			if (regId.equalsIgnoreCase("")) {
				Intent intent = new Intent(LoginActivity.this,
						HomeActivity.class);
				Bundle data = new Bundle();
				data.putInt("key_GMC", 0);
				data.putString("regId", regId);
				intent.putExtras(data);
				startActivity(intent);
				finish();
			} else {
				Intent intent = new Intent(LoginActivity.this,
						HomeActivity.class);
				Bundle data = new Bundle();
				data.putInt("key_GMC", 1);
				data.putString("regId", regId);
				intent.putExtras(data);
				startActivity(intent);
				finish();
			}

		}

	}

	// get Category
	public class VerySlowTaskCategory extends AsyncTask<Void, Void, Void> {
		TokenModel tokenModel = TokenModel.getInstance();
		TokenDTO token = tokenModel.getToken(LoginActivity.this);
		ArrayList<AnimalCategoryMasterDTO> arrData;
		String regId = "";

		public VerySlowTaskCategory(String _regId) {
			regId = _regId;
			arrData = new ArrayList<AnimalCategoryMasterDTO>();
			if(flagDialog){
				
				dialog2 = new Dialog(LoginActivity.this, R.style.NewDialog);
				dialog2.setContentView(R.layout.loading);

				dialog2.setCancelable(false);
				dialog2.findViewById(R.id.loading_icon).setBackgroundResource(
						R.drawable.spin_animation);
				frameAnimation2 = (AnimationDrawable) dialog2.findViewById(
						R.id.loading_icon).getBackground();
				dialog2.show();
				frameAnimation2.start();
			}
			
		}

		@Override
		protected Void doInBackground(Void... params) {
			AnimalCategoryMasterModel model = AnimalCategoryMasterModel
					.getInstance();
			model.deleteAnimal(LoginActivity.this);

			HttpClient client = new DefaultHttpClient();
			HttpGet method = new HttpGet(Constants.URL_GET_CATEGORY);
			method.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			method.setHeader("Authorization", token.getToken_type() + " "
					+ token.getAccess_token());
			try {
				HttpResponse response = client.execute(method);
				response.getEntity();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						(response.getEntity().getContent())));
				String output;
				System.out.println("Output from Server .... \n");
				StringBuilder builder = new StringBuilder();
				while ((output = br.readLine()) != null) {
					System.out.println(output);
					builder.append(output);
				}

				String strJson = builder.toString();
				if (strJson != null) {
					JSONArray jsonArr = new JSONArray(strJson);
					for (int i = 0; i < jsonArr.length(); i++) {
						JSONObject obj = jsonArr.getJSONObject(i);

						int Id = obj.getInt("Id");
						String AnimalCategory = obj.getString("AnimalCategory");
						int OrderNo = obj.getInt("OrderNo");
						obj.getString("UpdatedOn");

						AnimalCategoryMasterDTO categoryDTO = new AnimalCategoryMasterDTO();
						categoryDTO.setId(Id);
						categoryDTO.setAnimalCategory(AnimalCategory);
						categoryDTO.setOrderNo(OrderNo);
						categoryDTO.setUrlImages(Constants.URL_CATEGORY
								+ AnimalCategory + ".png");

						AnimalCategoryMasterModel modelCategory = AnimalCategoryMasterModel
								.getInstance();
						boolean flagCategory = modelCategory.getIdCategory(
								LoginActivity.this, Id);
						if (!flagCategory) {
							modelCategory.insertCategory(categoryDTO,
									LoginActivity.this);
						} else {
							modelCategory.updateCategory(categoryDTO,
									LoginActivity.this);
						}
						arrData.add(categoryDTO);

					}
				}

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if(flagDialog){
				dialog2.dismiss();
				frameAnimation2.stop();
			}
			
			new VerySlowTaskDelete(regId).execute();

		}

	}

	public static boolean deleteDirectory(File path) {
		if (path.exists()) {
			File[] files = path.listFiles();
			if (files == null) {
				return true;
			}
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return (path.delete());
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
}
